/*
 * net_broadcast.c
 *
 *  Created on: 2023年7月22日
 *      Author: mcealt_DS
 */

#include "net_broadcast.h"
#include "app_log.h"
#include <string.h>
#include "util.h"


static void RBF_Broadcast_packet_log(uint8_t *packet, uint16_t packetlen)
{
#if defined(CONFIG_LOG_RBFBROADCAST)
  DS_app_log_debug("packet(%d) is:", packetlen);
  DS_app_log_hexdump_debug("", packet, packetlen + RBF_MAC_PACKET_LEN_SIZE);
#else
  (void) packet;
  (void) packetlen;
#endif
}

static void RBF_gw_broadcast_payload_log(const RBFMacMessageGWBoardcast_t *msg)
{
#if defined(CONFIG_LOG_RBFBROADCAST)
  DS_app_log_debug("RBF_gw_download_payload_log msg is:\r\n");
  DS_app_log_debug("systemId = 0x%06X\r\n", msg->systemId);
  DS_app_log_debug("bseq = 0x%02X\r\n", msg->bseq);
  DS_app_log_debug("bretryAckCtrl = 0x%02X\r\n", msg->bretryAckCtrl);
  DS_app_log_debug("bTypeData ");
  if (msg->bTypeDataSize == 0 || msg->bTypeData == NULL)
    DS_app_log_debug(" = NULL ");
  else
  {
    DS_app_log_debug("(%d)", msg->bTypeDataSize);
    DS_app_log_hexdump_debug(" = ", msg->bTypeData, msg->bTypeDataSize);
  }
#else
  (void) msg;
#endif
}

/*
 * 网关广播payload
 */
// 解包
void RBF_gw_broadcast_payload_packetToMsg(uint8_t *packet, RBFMacMessageGWBoardcast_t *msg)
{
  msg->systemId = l_get_be24(packet + RBF_MAC_PAYLOAD_GW_BROADCAST_INDEX_SYSTEMID);
  msg->bretryAckCtrl = l_get_u8(packet + RBF_MAC_PAYLOAD_GW_BROADCAST_INDEX_BRETRYACKCTRL);
  msg->bTypeDataSize = *packet - RBF_MAC_PACKET_GW_BROADCAST_LEN - RBF_TAIL_LENGTH_MAX;
  msg->bTypeData = packet + RBF_MAC_PAYLOAD_GW_BROADCAST_INDEX_BTYPEDATA;
  RBF_gw_broadcast_payload_log(msg);
}
// 组包
void RBF_gw_broadcast_payload_msgToPacket(RBFMacMessageGWBoardcast_t msg, uint8_t *packet)
{
  l_put_be24(msg.systemId, packet + RBF_MAC_PAYLOAD_GW_BROADCAST_INDEX_SYSTEMID);
  l_put_u8(msg.bretryAckCtrl, packet + RBF_MAC_PAYLOAD_GW_BROADCAST_INDEX_BRETRYACKCTRL);
  if (msg.bTypeData == NULL)
    return;
  memmove(packet + RBF_MAC_PAYLOAD_GW_BROADCAST_INDEX_BTYPEDATA, msg.bTypeData, msg.bTypeDataSize);
  *packet = RBF_MAC_PACKET_GW_BROADCAST_LEN + msg.bTypeDataSize + RBF_TAIL_LENGTH_MAX;
  RBF_Broadcast_packet_log(packet, *packet);
}
